package com.yvon.maple.msg.parser;

import cn.hutool.core.collection.CollUtil;
import com.google.common.collect.Lists;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 简单字符串解析器
 *
 * @author : Yvon
 * @since : 2021-10-28
 */
public class SimpleStringMsgParser implements MsgParser<String> {

    @Override
    public String parse(String content, List<String> params) {
        if (CollectionUtils.isEmpty(params)) {
            return content;
        }

        return replace(content, params);
    }

    @Override
    public String parse(String content, String... params) {
        if (Objects.isNull(params) || params.length == 0) {
            return content;
        }

        return replace(content, Lists.newArrayList(params));
    }


    /**
     * Replace all string.
     *
     * @param content the content
     * @param values  the values
     * @return String
     * @author : Yvon / 2021-10-28
     */
    private String replace(String content, List<String> values) {
        return replace(content, values, 0);
    }


    /**
     * Replace all string.
     *
     * @param content the content
     * @param values  the values
     * @param index   the index
     * @return String
     * @author : Yvon / 2021-10-28
     */
    private String replace(String content, List<String> values, int index) {
        String pattern = PATTERN.replace(VARIABLE, String.valueOf(index));
        String value = values.get(index);

        content = replace(content, pattern, value);

        if (index == values.size() - 1) {
            return content;
        } else {
            return replace(content, values, index + 1);
        }
    }

    /**
     * Replace all string.
     *
     * @param content the content
     * @param values  the values
     * @param index   the index
     * @return String
     * @author : Yvon / 2021-10-28
     */
    @Override
    public String parse(String content, Map<String, String> map) {
        AtomicReference<String> s = new AtomicReference<>(content);
        if (CollUtil.isNotEmpty(map)) {
            map.keySet().forEach(key -> {
                String pattern = PATTERN.replace(VARIABLE, key);
                String value = map.get(key);
                s.set(replace(s.get(), pattern, value));
            });
        }
        return s.get();
    }
}
